<html>
<head>
<title>Scripts</title>

<script type="text/javascript" src="/js/json2.min.js"></script>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="/js/jquery-linedtextarea.js"></script>

<link rel="stylesheet" type="text/css" href="/css/ui-lightness/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="/css/jquery-linedtextarea.css" />

<style type="text/css">
.pageContent { margin-top: 25px; }
.compilestatus_error { background-color: #e06060; font-weight: bold; }
.compilestatus_warning { background-color: yellow; font-weight: bold; }
</style>
        
<script type="text/javascript">
var scriptID = -1;
var originalScriptData = '';

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

$(document).ready(function() {
    $('#verifyScript').click(function() { verifyScript(); return false; });
    $('#saveScript').click(function() { saveScript(false); return false; });
    $('#saveCloseScript').click(function() { saveScript(true); return false; });
    $('#closeScript').click(function() { closeScript(); return false; });
    $('#scriptData').linedtextarea();

    var id = getParameterByName("scriptid");
    if (id != "") {
        loadScript(id);
    }
    else {
        $('#scriptName').val('New Script');
    }
});

//
// Load the script with the given ID number into the editor.
//
function loadScript(id)
{
    $.ajax({
        url: "/json/script/" + id,
	type: "GET",
        success: function(data) {
            $('#scriptName').val(data['name']);
            $('#runType').val(data['type']);
            $('#scriptData').val(data['code']);
            scriptID = data['id'];
            originalScriptData = $('#scriptData').val();
        },
        error: function() {
            alert('Could not load script data.');
        }
    });
}

function closeScript()
{
    if ($('#scriptData').val() != originalScriptData) {
        if (confirm('Discard changes and close?') == false)
            return;
    }

    parent.$.fn.colorbox.close();
}

function verifyScript()
{
    $.ajax({
        url: "/json/script/verify",
	type: "POST",
	data: $('#scriptData').val(),
        success: function(data) {
            if (data["status"] == 1) {
                $('#scriptStatus').text('Compiled OK');
            }
            else {
                var html = '';
                for (i = 0; i < data['errors'].length; i++) {
                    var err = data['errors'][i];

                    html += '<span class="compilestatus_' + (err['error'] == true ? 'error' : 'warning') + '">';
                    html += 'Line ' + err['lineno'] + ': ' + err['message'];
                    html += '</span><br />';
                }

                $('#scriptStatus').html(html);
            }
	    alert(data["status"]);
        },
        error: function() {
            alert('Could not load data.');
        }
    });
}

function saveScript(closeOnSuccess)
{
    var content = { name: $('#scriptName').val(),
		runtype: parseInt($('#runType').val()),
		code: $('#scriptData').val()
		};
    var url = (scriptID == -1 ? "/json/script" : "/json/script/" + scriptID);

    $.ajax({
        url: url,
	type: "PUT",
	data: JSON.stringify(content),
	dataType: 'json',
	beforeSend: function(x) {
	  if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF=8"); }
	},
        success: function(data) {
            if (data["id"] != -1) {
                $('#scriptStatus').text('Saved OK as id ' + data["id"] + JSON.stringify(data));
                scriptID = data["id"];
                originalScriptData = $('#scriptData').val();
                if (closeOnSuccess == true)
                    parent.$.fn.colorbox.close();
            }
            else {
                $('#scriptStatus').text('Could not save.');
            }
        },
        error: function(data) {
            alert('Could not load data: ' + data);
        }
    });
}
</script>

</head>

<body>
    <div class="pageHeader">
        <div>Script Name: <input type="text" size="30" id="scriptName" value="" /></div>
        <div>Run Type: <select id="runType"><option value="0">Run Once</option><option value="1">Daemon</option></select></div>
    </div>
    <div class="pageContent">
	<p style="float: left; width: 640px; height: 480px; margin: 0px;">
	    <textarea id="scriptData" style="width: 100%; height: 100%" spellcheck="false"></textarea>
	</p>
        <div style="margin-left: 655px; height: 480px;">
	    <p>
                <a id="verifyScript" href="#">Verify Script</a><br />
                <a id="saveScript" href="#">Save Script</a><br />
                <a id="saveCloseScript" href="#">Save &amp; Close</a><br />
                <a id="closeScript" href="#">Close</a><br />
            </p>
        </div>

        <div style="margin-top: 10px;" id="scriptStatus">
        </div>
    </div>
</body>

</html>
